<template>
    <div>
        <el-card>
            <el-alert  center title="添加商品信息" type="info" show-icon :closable="false"></el-alert>
            <el-steps align-center :active="StepActive*1" finish-status="success" style="margin:10px 0;">
                <el-step title="基本信息"></el-step>
                <el-step title="商品参数"></el-step>
                <el-step title="商品属性"></el-step>
                <el-step title="商品图片"></el-step>
                <el-step title="商品内容"></el-step>
            </el-steps>
            <el-form ref="AddGoodsFormRef" :model="AddGoodsForm" :rules="AddGoodsFormRules" label-width="80px">
                <el-tabs v-model="StepActive" tab-position="left" :before-leave="beforeLeave" @tab-click="TabChange">
                    <el-tab-pane label="基本信息" name="0">
                        <el-form-item label="商品名称" prop="goods_name">
                            <el-input v-model="AddGoodsForm.goods_name"></el-input>
                        </el-form-item>
                        <el-form-item label="商品价格" prop="goods_price">
                            <el-input v-model="AddGoodsForm.goods_price"></el-input>
                        </el-form-item>
                        <el-form-item label="商品数量" prop="goods_number">
                            <el-input v-model="AddGoodsForm.goods_number"></el-input>
                        </el-form-item>
                        <el-form-item label="商品重量" prop="goods_weight">
                            <el-input v-model="AddGoodsForm.goods_weight"></el-input>
                        </el-form-item>
                        <el-form-item label="商品分类">
                            <el-cascader style="width:100%" v-model="AddGoodsForm.goods_cat" :options="GoodsCateList" :props="{ expandTrigger: 'hover',...GoodsCateOptions }"></el-cascader>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品参数" name="1">
                        <el-form-item v-for="item in manyDataList" :key="item.attr_id" :label="item.attr_name">
                            <el-checkbox-group v-model="item.attr_vals">
                                <el-checkbox v-for="element in item.attr_vals" :key="element" :label="element" border>{{ element }}</el-checkbox>
                            </el-checkbox-group>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品属性" name="2">
                        <el-form-item v-for="item in onlyDataList" :key="item.attr_id" :label="item.attr_name">
                            <el-input v-model="item.attr_vals"></el-input>
                        </el-form-item>
                    </el-tab-pane>
                    <el-tab-pane label="商品图片" name="3">
                        <el-upload class="upload-demo" action="http://127.0.0.1:8888/api/private/v1/upload" :on-remove="handleRemovePic" :on-success="handleSuccessPic" list-type="picture" :headers="getToken">
                            <el-button size="small" type="primary">点击上传</el-button>
                            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
                        </el-upload>
                    </el-tab-pane>
                    <el-tab-pane label="商品内容" name="4">
                        <quill-editor v-model="AddGoodsForm.goods_introduce" ref="quillEditorRef">
                        </quill-editor>
                        <el-button type="primary" @click="AddGoods">添加商品</el-button>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import {Get_GoodsData,Add_GoodsListData} from '@/api/goods.js';
import {Get_CateParams} from '@/api/params.js';
import { quillEditor } from 'vue-quill-editor';
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
import _ from 'lodash';
    export default {
        data(){
            return{
                StepActive:"0",//步骤条选中参数 数值类型
                AddGoodsForm:{//添加商品的参数
                    goods_name:'',//商品名字
                    goods_price:1,//商品价格
                    goods_number:1,//商品数量
                    goods_weight:1,//商品重量
                    goods_cat:[],//商品选中的分类层级
                    goods_introduce:'',//商品说明
                    pics:[],//商品图片
                    attrs:[]//商品参数
                },
                AddGoodsFormRules:{//form表单的校验规则
                    goods_name:[
                        { required: true, message: '请输入商品名称', trigger: 'blur' }
                    ],
                    goods_price:[
                        { required: true, message: '请输入商品价格', trigger: 'blur' }
                    ],
                    goods_number:[
                        { required: true, message: '请输入商品数量', trigger: 'blur' }
                    ],
                    goods_weight:[
                        { required: true, message: '请输入商品重量', trigger: 'blur' }
                    ]
                },
                GoodsCateList:[],//存储获取到的数据
                selectedKeys:[],//级联选择器选中绑定的数组
                GoodsCateOptions:{//配置选项
                        label:'cat_name',//指定选项标签为选项对象的某个属性值
                        value:'cat_id',//指定选项的值为选项对象的某个属性值
                        children:'children'//指定选项的子选项为选项对象的某个属性值
                },
                manyDataList:[],//存储动态参数数据
                onlyDataList:[],//存储静态参数数据'
                getToken:{//上传图片时需要的token
                    Authorization:window.sessionStorage.getItem('token')
                }
            }
        },
        mounted(){
            this.getGoodsList(); 
        },
        components: {
            quillEditor//富文本编辑器
        },
        computed:{
            cat_id(){//获取最新的cat_id
                if(this.AddGoodsForm.goods_cat.length === 3){//如果为3
                    return this.AddGoodsForm.goods_cat[this.AddGoodsForm.goods_cat.length - 1]//将最后的cat_id存储
                }else{//否则
                    return null;//返回空
                }
            }
        },
        methods:{
            async getGoodsList(){//获取所有数据
                const result = await Get_GoodsData({type:3})//获取层级为3
                if(result.meta.status != 200){//如果状态码不为200返回错误提示框
                    return this.$message.error('请求失败')
                }
                console.log(result);
                this.GoodsCateList = result.data;//赋值
            },
            beforeLeave(ActiveName,oldActiveName){//当标签页更改时触发 第一参数为要去的标签页name 第二个参数是之前的标签页name
                console.log(ActiveName,oldActiveName)//为字符串下标
                if(oldActiveName === '0' && this.AddGoodsForm.goods_name === '' && this.AddGoodsForm.goods_cat.length === 0){//如果旧name为0并且goods_name为空 并且goods_cat长度为0
                    this.$message.error('请填写完整信息')//弹出提示框
                    return false;//并且不让过去
                }
            },
            async TabChange(){//标签页更改时触发
                if(this.StepActive == '1'){//如果选中的值为1
                    const result = await Get_CateParams({//获取动态参数
                        method:'get',
                        url:`categories/${this.cat_id}/attributes`,
                        params:{
                            sel:'many'
                        }
                    })
                    if(result.meta.status != 200){//如果状态码不为200弹出错误提示框
                        return this.$message.error('请求失败')
                    }
                    result.data.forEach((item)=>(//将attr_vals格式改为字符串
                        item.attr_vals = item.attr_vals.length == 0 ? [] : item.attr_vals.split(',')//需要判断数组是否为空数组
                    ))
                    this.manyDataList = result.data;//赋值
                }
                if(this.StepActive == '2'){//如果选中的值是2
                    const result = await Get_CateParams({//发送请求获取静态参数
                        method:'get',
                        url:`categories/${this.cat_id}/attributes`,
                        params:{
                            sel:'only'
                        }
                    })
                    if(result.meta.status != 200){//如果状态码不为200弹出错误提示框
                        return this.$message.error('请求失败')
                    }
                    this.onlyDataList = result.data;//赋值
                }
            },
            // 删除图片触发
            handleRemovePic(file, fileList) {
                console.log(file, fileList);//第一个参数为图片信息 第二个参数为所有图片列表信息
                const filePath = file.response.data.tmp_path;//将图片的tmp_path存储起来
                const index = this.AddGoodsForm.pics.findIndex((item)=>{//在this.AddGoodsForm.pics中查找
                    item.tmp_path = filePath//返回index
                });
                this.AddGoodsForm.pics.splice(index,1);//根据index删除图片
            },
            // 文件上传成功时的钩子
            handleSuccessPic(response, file, fileList){
                console.log(response, file, fileList);//response为响应数据 file为图片信息 fileList为图片列表
                this.AddGoodsForm.pics.push({tmp_path:response.data.tmp_path});//上传成功的话 将图片的临时路径存储起来
            },
            // 添加商品
            AddGoods(){
                console.log(this.AddGoodsForm);
                const newForm = _.cloneDeep(this.AddGoodsForm);//深拷贝克隆一份要发送的参数
                newForm.goods_cat = newForm.goods_cat.join(',');//将goods_cat处理格式为逗号分隔的字符串
                this.manyDataList.forEach((item)=>{//在manyDataList中拷贝数据
                    const manyItem = {attr_id:item.attr_id,attr_vals:item.attr_vals}
                    newForm.attrs.push(manyItem)//添加到attrs中
                })
                this.onlyDataList.forEach((iteM)=>{//在onlyDataList中拷贝数据
                    const onlyItem = {attr_id:iteM.attr_id,attr_vals:iteM.attr_vals}
                    newForm.attrs.push(onlyItem)//添加到attrs中
                })
                console.log(newForm);
                this.$refs.AddGoodsFormRef.validate(async (valid)=>{//表单校验
                    if(!valid){//如果校验失败
                        return this.$message.error('请填写完整')//弹出错误提示框
                    }
                    const result = await Add_GoodsListData(newForm);//如果成功发送添加商品请求
                    console.log(result);
                    if(result.meta.status != 201){//如果状态码不为201 弹出错误提示框
                        return this.$message.error('添加失败')
                    }
                    this.$message.success('添加成功');//否则弹出成功提示框
                    this.$router.push('/goods')//并跳转到/goods页面
                })
            }
        }
    }
</script>

<style lang="scss" scoped>

</style>